<script>
  export default {
    name: 'InsertTable',
    emits: ['click'],
    data() {
      return {
        rows: 0,
        cols: 0,
        visible: false
      }
    },
    methods: {
      handleMouseEnter(i,j) {
        this.rows = i
        this.cols = j
      },
      handleMouseLeave() {
        this.rows = 0
        this.cols = 0
      },
      handleClick() {
        if (this.rows === 0 || this.cols === 0) return
        this.$emit('click', this.rows, this.cols)
        this.toggleVisible()
        this.rows = 0
        this.cols = 0
      },
      toggleVisible() {
        this.visible = !this.visible
      }
    }
  }
</script>

<template>
  <div class="tx-table" @mouseleave="visible = false">
    <div class="tx-table-container">
      <div class="tx-button" @click="toggleVisible" title="表格">
        <i class="iconfont icon-sheet"></i>
      </div>
      <div v-if="visible" class="tx-table-box">
        <table class="tx-table-warp">
          <tr v-for="i in 8" :key="'row'+ i" class="tx-table-row">
            <td v-for="j in 8" :key="'col'+ j" class="tx-table-col" :class="{'tx-table-col-select': rows >= i && cols >= j }" @mouseenter="handleMouseEnter(i,j)" @mouseleave="handleMouseLeave" @click="handleClick"></td>
          </tr>
        </table>
        <div>
          rows: <input v-model="rows" />
          cols: <input v-model="cols" />
          <button @click="handleClick">插入</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
  .tx-table {
    display: inline-block;
  }
  .tx-table-container {
    background-color: #ffffff;
  }
  .tx-table-box {
    background: #fff;
    border: 0 solid rgba(0,0,0,.25);
    box-shadow: 0 1px 4px rgba(0,0,0,.25);
    border-radius: 4px;
    position: absolute;
    padding: 8px;
    z-index: 10;
  }
  .tx-table-warp {
    width: 100%;
    border: 1px solid #ccc;
    border-collapse: collapse;
  }
  .tx-table-row,
  .tx-table-col {
    border: 1px solid #ccc;
    width: 24px;
    height: 18px;
  }
  .tx-table-col-select {
    background: #0000ff60;
  }
</style>